#include "onenet_edp.h"
/*----------------------------???-----------------------------------------*/
#define ERR_CREATE_SOCKET   -1 
#define ERR_HOSTBYNAME      -2 
#define ERR_CONNECT         -3 
#define ERR_SEND            -4
//#define ERR_TIMEOUT         -5
#define ERR_RECV            -6

#define MSG_NOSIGNAL 0

#define RELAYA_ID "relaya"     //
#define TEMP_ID   "temp"     //
#define HUMI_ID   "humi"     //
#define RELAYB_ID "relayb"     //
#define IMAGE_ID   "image"     //
#define TIME_ID   "sys_time"
#define DEV_ID1  "28371451"
#define DEV_ID2  "29500970"
#define API_KEY "jRBQTvs11gQQwK5jHBMzIn8ei2Q="

#define SERVER_ADDR "jjfaedp.hedevice.com"    //OneNet EDP server addr
//#define SERVER_ADDR "api.heclouds.com"
//#define SERVER_ADDR "183.230.40.39"
#define SERVER_PORT 876                       //OneNet EDP server port


onenet_ctl_t myctl[5]= {{TEMP_ID, 1, 1},{HUMI_ID, 1, 1},
                                      {RELAYB_ID, 1, 1},};
typedef struct onenet_upload
{
    u32_t image_peroid;
    u32_t image_tick;
    u32_t time_peroid;
    u32_t time_tick;
}onenet_upload_t;

onenet_upload_t my_upload = {10000, 0, 5000, 0}; //upload image every 6s, upload time every 4s

static int g_is_encrypt = 0;

/*
 * buffer???????
 */
void hexdump(const unsigned char *buf, uint32 num)
{
    uint32 i = 0;
    for (; i < num; i++) 
    {
        Printf("%02X ", buf[i]);
        if ((i+1)%8 == 0) 
            Printf("\n");
    }
    Printf("\n");
}

/* 
 * ???:  Open
 * ??:    ??socket?????????
 * ??:    addr    ip??
 *          protno  ???
 * ??:    ??????????socket????????, ?????????socket api
 * ??socket api:  
 *          socket, gethostbyname, connect
 * ???:  ?? (int32)
 *          <=0     ??socket??
 *          >0      socket???
 */
int32 Open(const char *addr, int16 portno)
{
    int32 sockfd;
    struct sockaddr_in serv_addr;
    struct hostent *server;
		
    /* ??socket??? */
    sockfd = socket(AF_INET, SOCK_STREAM, 0);
    if (sockfd < 0) {
        Printf("ERROR opening socket\r\n");
        return ERR_CREATE_SOCKET; 
    }
    server = gethostbyname(addr);
    if (server == NULL) {
        Printf("ERROR, no such host\n");
        return ERR_HOSTBYNAME;
    }



		memset((char *) &serv_addr, 0, sizeof(serv_addr));
    serv_addr.sin_family = AF_INET;
    memcpy( (char *)&serv_addr.sin_addr.s_addr,
						(char *)server->h_addr, 
          server->h_length);
    serv_addr.sin_port = htons(portno);
    if (lwip_connect(sockfd,(struct sockaddr *) &serv_addr,sizeof(serv_addr)) < 0) 
    {
        Printf("ERROR connecting\n");
        return ERR_CONNECT;
    }
#ifdef _DEBUG
    Printf("[%s] connect to server %s:%d succ!...\n", __func__, addr, portno);
#endif
    return sockfd;
}
/* 
 * ???:  DoSend
 * ??:    ?buffer??len??????(??)socket???sockfd, ???????(???)???.
 * ??:    sockfd  socket??? 
 *          buffer  ??????
 *          len     ??????
 * ??:    ????????????????, ?????????socket api
 *          ????, ?????????, ??????????? > socket??????, ??send??????.
 * ??socket api:  
 *          send
 * ???:  ?? (int32)
 *          <=0     ????
 *          >0      ????????
 */
int32 DoSend(int32 sockfd, const char* buffer, uint32 len)
{
    int32 total  = 0;
    int32 n = 0;
    while (len != total)
    {
        /* ????len - total?????? */
        n = send(sockfd,buffer + total,len - total,MSG_NOSIGNAL);
        if (n <= 0)
        {
          //  fPrintf(stderr, "ERROR writing to socket\n");
            return n;
        }
        /* ?????n?????? */
        total += n;
    }
    /* wululu test print send bytes */
    hexdump((const unsigned char *)buffer, len);
    return total;
}
int16 get_number(char * str)
{
    int16 ret = 0;
    int i = 0;
    if(str == NULL) return -1;
    while(*str == ' ' || *str == ':') str++;
	
    while(str[i] >= '0' && str[i] <= '9')
    {
        ret = ret*10+(str[i] - '0');
        i++;
        if(i > 5) break;
    }
	
    if(i == 0) return -1;
	
    return ret;
}
int16 update_stream(char *str, int16 num)
{
    int i = 0;
    if(str == NULL) return -1;
	
    while(*str == ' ' || *str == '"') str++;
    
    for(i = 0; i < 5; i++)
    {
        if(strncmp(str, myctl[i].str, 6) == 0)
        {
            if(myctl[i].value != num)
            {
                myctl[i].value = num;
                myctl[i].change = 1;
            }
    			
            return 0;
        }
    }

    return -1;
}
void update_ctl(void)
{
	if(myctl[0].change)
	{
            Printf("led0 change to [%d]\n", myctl[0].value);
		
	}
	if(myctl[1].change)
	{
	    Printf("led1 change to [%d]\n", myctl[1].value);
	}
}
static char buffer[512];
static char cmd_buf[50];
static char req_buf[50];

int recv_func(int arg)
{
    int sockfd = arg,i;
    int error = 0;
    int n, rtn;
    uint8 mtype, jsonorbin;
    
    RecvBuffer* recv_buf = NewBuffer();
    EdpPacket* pkg = NULL;
    EdpPacket* pkg_send = NULL;
    
    char* src_devid;
    char* push_data;
    uint32 push_datalen;

    cJSON* save_json;
    char* save_json_str;

    cJSON* desc_json;
    char* desc_json_str;
    char* save_bin; 
    uint32 save_binlen;
    int ret = 0;

    char *cmdid = NULL;
    uint16 cmdid_len = 0;
    char* req = NULL;
    uint32 req_len = 0;
    int16 num = -1;
    do
    {
        n = lwip_recv(sockfd, buffer, 512, 0);
        if (n <= 0)
        {
            Printf("recv error, bytes: %d\n", n);
						error = -1;
            break;
        }

        //Printf("recv from server, bytes: %d\n", n);
		
        WriteBytes(recv_buf, buffer, n);
        while (1)
        {   
            if ((pkg = GetEdpPacket(recv_buf)) == 0)
            {
                //Printf("need more bytes...\n");
                break;
            }
		
            mtype = EdpPacketType(pkg);
            switch(mtype)
            {
                case CONNRESP:
                    rtn = UnpackConnectResp(pkg);
                    Printf("recv connect resp, rtn: %d\n", rtn);
                    break;
                case PUSHDATA:
                    UnpackPushdata(pkg, &src_devid, &push_data, &push_datalen);
                    Printf("recv push data, src_devid: %s, push_data: %s, len: %d\n", 
                            src_devid, push_data, push_datalen);
                    mem_free(src_devid);
                    mem_free(push_data);
                    break;
                case SAVEDATA:
                    if (UnpackSavedata(pkg, &src_devid, &jsonorbin) == 0)
                    {
                        if (jsonorbin == 0x01) 
                        {/* json */
                            ret = UnpackSavedataJson(pkg, &save_json);
                            save_json_str=cJSON_Print(save_json);
                            Printf("recv save data json, ret = %d, src_devid: %s, json: %s\n", 
                                   ret, src_devid, save_json_str);
                            mem_free(save_json_str);
                            cJSON_Delete(save_json);
                        }
                        else if (jsonorbin == 0x02)
                        {/* bin */
                            UnpackSavedataBin(pkg, &desc_json, (uint8**)&save_bin, &save_binlen);
                            desc_json_str=cJSON_Print(desc_json);
                            Printf("recv save data bin, src_devid: %s, desc json: %s, bin: %s, binlen: %d\n", 
                                    src_devid, desc_json_str, save_bin, save_binlen);
                            mem_free(desc_json_str);
                            cJSON_Delete(desc_json);
                            mem_free(save_bin);
                        }
                        free(src_devid);
                    }
                    break;
                case PINGRESP:
                    UnpackPingResp(pkg); 
                    Printf("recv ping resp\n");
                    break;
                case CMDREQ:
                    if(UnpackCmdReq(pkg, &cmdid, &cmdid_len, &req, &req_len) != 0)
                    {
                        break;
                    }
                    memset(cmd_buf, 0, 50);
                    memset(req_buf, 0, 50);
                    memcpy(cmd_buf, cmdid, cmdid_len);
                    memcpy(req_buf, req, req_len);
                    Printf("[Cmd]  CMDREQ cmd[%s]cmdlen[%d], req[%s]reqlen[%d]\n", \
                                                               cmd_buf, cmdid_len, req_buf, req_len);
                    num = get_number(req+7);
                    if(num < 0)
                    {
                        mem_free(cmdid);
                        mem_free(req);
                        break;
                    }

		     update_stream(req, num);
		     update_ctl();
             
                    pkg_send = PacketCmdResp(cmdid, cmdid_len, req, req_len);
                    ret = DoSend(sockfd, (const char *)pkg_send->_data, pkg_send->_write_pos);
	            Printf("[Cmd]  PacketCmdResp DoSend: ret = %d\n", ret);
                    DeleteBuffer(&pkg_send);
                    mem_free(cmdid);
                    mem_free(req);
                    break;
                default:
                    Printf("unknown type...\n");
                    break;
            }
            DeleteBuffer(&pkg);
        }
    }while(0);
	
    DeleteBuffer(&recv_buf);

    return error;
}
/* 
 * ???:  recv_thread_func
 * ??:    ??????
 * ??:    arg     socket???
 * ??:    ??????????socket???????, ?????????socket api
 *          ????, ?????????, ??????????? > socket??????, ??recv??????.
 * ??socket api:  
 *          recv
 * ???:  ?
 */
void recv_thread_func(void* arg)
{
    int sockfd = *(int*)arg;
    int error = 0;
    int n, rtn;
    uint8 mtype, jsonorbin;
    char buffer[1024];
    RecvBuffer* recv_buf = NewBuffer();
    EdpPacket* pkg;
    
    char* src_devid;
    char* push_data;
    uint32 push_datalen;

    cJSON* save_json;
    char* save_json_str;

    cJSON* desc_json;
    char* desc_json_str;
    char* save_bin; 
    uint32 save_binlen;
    unsigned short msg_id;
    unsigned char save_date_ret;

    char* cmdid;
    uint16 cmdid_len;
    char*  cmd_req;
    uint32 cmd_req_len;
    EdpPacket* send_pkg;
    char* ds_id;
    double dValue = 0;
    int iValue = 0;
    char* cValue = NULL;

    char* simple_str = NULL;
    char cmd_resp[] = "ok";
    unsigned cmd_resp_len = 0;

	DataTime stTime = {0};

    FloatDPS* float_data = NULL;
    int count = 0;
    int i = 0;

    struct UpdateInfoList* up_info = NULL;

#ifdef _DEBUG
    Printf("[%s] recv thread start ...\n", __func__);
#endif

    while (error == 0)
    {
        /* ????1024?????? */
        n = lwip_recv(sockfd, buffer, 1024, MSG_NOSIGNAL);
        if (n <= 0)
            break;
        Printf("recv from server, bytes: %d\n", n);
        /* wululu test print send bytes */
        hexdump((const unsigned char *)buffer, n);
        /* ?????n?????? */
        WriteBytes(recv_buf, buffer, n);
        while (1)
        {
            /* ???????EDP? */
            if ((pkg = GetEdpPacket(recv_buf)) == 0)
            {
                Printf("need more bytes...\n");
                break;
            }
            /* ????EDP?????? */
            mtype = EdpPacketType(pkg);
#ifdef _ENCRYPT
            if (mtype != ENCRYPTRESP){
                if (g_is_encrypt){
                    SymmDecrypt(pkg);
                }
            }
#endif
            /* ????EDP??????, ???EDP??? */
            switch(mtype)
            {
#ifdef _ENCRYPT
            case ENCRYPTRESP:
                UnpackEncryptResp(pkg);
                break;
#endif
            case CONNRESP:
                /* ??EDP? - ???? */
                rtn = UnpackConnectResp(pkg);
                Printf("recv connect resp, rtn: %d\n", rtn);
                break;
            case PUSHDATA:
                /* ??EDP? - ???? */
                UnpackPushdata(pkg, &src_devid, &push_data, &push_datalen);
                Printf("recv push data, src_devid: %s, push_data: %s, len: %d\n",
                       src_devid, push_data, push_datalen);
                free(src_devid);
                free(push_data);
                break;
            case UPDATERESP:
                UnpackUpdateResp(pkg, &up_info);
                while (up_info){
                    Printf("name = %s\n", up_info->name);
                    Printf("version = %s\n", up_info->version);
                    Printf("url = %s\nmd5 = ", up_info->url);
                    for (i=0; i<32; ++i){
                        Printf("%c", (char)up_info->md5[i]);
                    }
                    Printf("\n");
                    up_info = up_info->next;
                }
                FreeUpdateInfolist(up_info);
                break;

            case SAVEDATA:
                /* ??EDP? - ???? */
                if (UnpackSavedata(pkg, &src_devid, &jsonorbin) == 0)
                {
                    if (jsonorbin == kTypeFullJson
                        || jsonorbin == kTypeSimpleJsonWithoutTime
                        || jsonorbin == kTypeSimpleJsonWithTime)
                    {
                        Printf("json type is %d\n", jsonorbin);
                        /* ??EDP? - json???? */
                        /* UnpackSavedataJson(pkg, &save_json); */
                        /* save_json_str=cJSON_Print(save_json); */
                        /* Printf("recv save data json, src_devid: %s, json: %s\n", */
                        /*     src_devid, save_json_str); */
                        /* free(save_json_str); */
                        /* cJSON_Delete(save_json); */

                        /* UnpackSavedataInt(jsonorbin, pkg, &ds_id, &iValue); */
                        /* Printf("ds_id = %s\nvalue= %d\n", ds_id, iValue); */

                        //UnpackSavedataDouble(jsonorbin, pkg, &ds_id, &dValue);
                        Printf("ds_id = %s\nvalue = %f\n", ds_id, dValue);

                        /* UnpackSavedataString(jsonorbin, pkg, &ds_id, &cValue); */
                        /* Printf("ds_id = %s\nvalue = %s\n", ds_id, cValue); */
                        /* free(cValue); */

                        free(ds_id);
				
                    }
                    else if (jsonorbin == kTypeBin)
                    {/* ??EDP? - bin???? */
                        UnpackSavedataBin(pkg, &desc_json, (uint8**)&save_bin, &save_binlen);
                        desc_json_str=cJSON_Print(desc_json);
                        Printf("recv save data bin, src_devid: %s, desc json: %s, bin: %s, binlen: %d\n",
                               src_devid, desc_json_str, save_bin, save_binlen);
                        free(desc_json_str);
                        cJSON_Delete(desc_json);
                        free(save_bin);
                    }
                    else if (jsonorbin == kTypeString ){
                        UnpackSavedataSimpleString(pkg, &simple_str);
			    
                        Printf("%s\n", simple_str);
                        free(simple_str);
                    }else if (jsonorbin == kTypeStringWithTime){
						UnpackSavedataSimpleStringWithTime(pkg, &simple_str, &stTime);
			    
                        Printf("time:%u-%02d-%02d %02d-%02d-%02d\nstr val:%s\n", 
							stTime.year, stTime.month, stTime.day, stTime.hour, stTime.minute, stTime.second, simple_str);
                        free(simple_str);
					}else if (jsonorbin == kTypeFloatWithTime){
                        if(UnpackSavedataFloatWithTime(pkg, &float_data, &count, &stTime)){
                            Printf("UnpackSavedataFloatWithTime failed!\n");
                        }

                        Printf("read time:%u-%02d-%02d %02d-%02d-%02d\n", 
                            stTime.year, stTime.month, stTime.day, stTime.hour, stTime.minute, stTime.second);
                        Printf("read float data count:%d, ptr:[%p]\n", count, float_data);
                        
                        for(i = 0; i < count; ++i){
                            Printf("ds_id=%u,value=%f\n", float_data[i].ds_id, float_data[i].f_data);
                        }

                        free(float_data);
                        float_data = NULL;
                    }
                    free(src_devid);
                }else{
                    Printf("error\n");
                }
                break;
            case SAVEACK:
                UnpackSavedataAck(pkg, &msg_id, &save_date_ret);
                Printf("save ack, msg_id = %d, ret = %d\n", msg_id, save_date_ret);
                break;
            case CMDREQ:
                if (UnpackCmdReq(pkg, &cmdid, &cmdid_len,
                                 &cmd_req, &cmd_req_len) == 0){
                    /*
                     * ??????????????,?????????,??????2???"ok"?
                     * ????????
                     */
                    cmd_resp_len = strlen(cmd_resp);
                    send_pkg = PacketCmdResp(cmdid, cmdid_len,
                                             cmd_resp, cmd_resp_len);
#ifdef _ENCRYPT
                    if (g_is_encrypt){
                        SymmEncrypt(send_pkg);
                    }
#endif
                    DoSend(sockfd, (const char*)send_pkg->_data, send_pkg->_write_pos);
                    DeleteBuffer(&send_pkg);
		    
                    free(cmdid);
                    free(cmd_req);
                }
                break;
            case PINGRESP:
                /* ??EDP? - ???? */
                UnpackPingResp(pkg);
                Printf("recv ping resp\n");
                break;

            default:
                /* ?????? */
                error = 1;
                Printf("recv failed...\n");
                break;
            }
            DeleteBuffer(&pkg);
        }
    }
    DeleteBuffer(&recv_buf);

#ifdef _DEBUG
    Printf("[%s] recv thread end ...\n", __func__);
#endif
}
void usage(char* name){
 //   Printf("Usage:%s [options]\n", basename(name));
    Printf("-h List help document\n");
    Printf("-i The ip of the edpacc\n");
    Printf("-p The port of the edpacc\n");
    Printf("-s Assign the dev_id of the source\n");
    Printf("-d Assign the dev_id of the destination\n");
    Printf("-a Assign the API key of the source\n");
    Printf("-l Assign the name of the datastream for test 'save json data'\n" );
    Printf("-v Assign the value of the datastream for test 'save json data'\n");
	Printf("-t Assign the time of the datastream for test 'save string data'\n");
    Printf("-E Encrypt\n");
    exit(0);
}
char *get_picture(int *len)
{
    FILE * fp = NULL;
    int n = 0;
    char * ret = NULL;
    static int i = 1;
    char name[50] = {0,};
    sprintf(name, "pics/image%d.jpg", i);
    i++;
    if(i == 11) i = 1;

    if((fp=fopen(name,"rb"))== NULL)
    {
        Printf("The file %s can not be opened.\n",name);
        return NULL;
    }
    do
    {
        fseek(fp,0L,SEEK_END);  
        n = ftell(fp);
        if( n < 0 || n > 20*1024)
        {
            Printf("The file [%s] too large.\n", name);
            break;
        }

        fseek(fp,0L,SEEK_SET);
		
        ret = (char *)malloc(n);
        if(ret == NULL)
        {
            Printf("malloc [%d] fail.\n", n);
            break;
        }

        if(fread(ret, 1, n, fp) <= 0)
        {
            Printf("fread fail.\n");
            free(ret);
            break;
        }
        *len = n;
        Printf("[image]fread [%s] return len[%d].\n", name, n);
        fclose(fp);
        return ret;

	}while(0);

	fclose(fp);
	return NULL;
}
EDPKIT_DLL
EdpPacket* EDP_PacketPushData(const char* dst_devid,
                             const char* msg, uint32 msg_len)
{
    EdpPacket* pkg = NewBuffer();
    uint32 remain_len,i;
		//Byte0:pushdata??-----------------------------------------------------------
		WriteByte(pkg, PUSHDATA);
		remain_len = 2 + strlen(dst_devid) + msg_len;
		 WriteRemainlen(pkg, remain_len);
		WriteByte(pkg, 0x00);
		WriteByte(pkg, 0x05);
		//????----------------------------------------------------------------------
		/* DEVID */
		WriteStr(pkg, dst_devid);
		/* DEVID */
		WriteStr(pkg, msg);
		return pkg;
}
int write_func(int arg)
{
    int sockfd = arg;
    int image_len = 0;
    char *image_data = NULL;
    EdpPacket* send_pkg = NULL;
    cJSON *desc_json;
    int32 ret = 0, flag = 0;
    uint32_t data = 0;
    //char text[25] = {0};
    char text_bin[]="{\"ds_id\": \"image\"}";
		char keep_alive[2] = {0x12,0x00};
    int i = 0;
    //(1) upload led status
//		myctl[0].change = 1;
//		myctl[0].value = rand()%50 + 10;
    for(i = 0; i < 3; i++)
    {
			if(myctl[i].change)
			{
				send_pkg = PacketSavedataInt(kTypeFullJson, NULL, myctl[i].str, (int)myctl[i].value, 0, NULL);
				if(NULL == send_pkg)
				{
					Printf("[%s] PacketSavedataInt error\n", myctl[i].str);
					return -1;
				}
				Printf("0send_pkg->_write_pos:%d ",send_pkg->_write_pos);
				ret = DoSend(sockfd, (const char*)send_pkg->_data, send_pkg->_write_pos);
				DeleteBuffer(&send_pkg);
				send_pkg = NULL;
					
				flag++;
				myctl[i].change = 0;
			}
    }

//    //(1) send current alarm status to onenet. 
//    if(sys_now()- my_upload.time_tick >= my_upload.time_peroid)
//    {
//			send_pkg = PacketSavedataInt(kTypeFullJson, NULL, TIME_ID, (int)sys_now()/1000, 0, NULL);
//			if(NULL == send_pkg)
//			{
//				Printf("[time] PacketSavedataInt error\n");
//				return -1;
//			}
//			ret = DoSend(sockfd, (const char *)send_pkg->_data, send_pkg->_write_pos);
//			Printf("[time] DoSend: ret = %d\n", data,(int)ret);
//			DeleteBuffer(&send_pkg);
//			send_pkg = NULL;

//			flag++;
//			my_upload.time_tick = sys_now();
//    }
    //(2) try to send a picture to onenet
//    if(sys_now()- my_upload.image_tick >= my_upload.image_peroid)
//    {	
//	image_data = get_picture(&image_len);
//	if(image_data == NULL)
//	{
//	    my_upload.image_tick = sys_now();
//            Printf("[image]get_picture error\n");
//	    return 0;
//	}
//        desc_json=cJSON_Parse(text_bin);
//    //    send_pkg = PacketSavedataBin(NULL, desc_json, (const uint8*)image_data, image_len);

//	free(image_data);
//	cJSON_Delete(desc_json);
//	if(NULL == send_pkg)
//	{
//		Printf("[image] PacketSavedataBin error\n");
//		return -1;
//	}

//	ret = DoSend(sockfd, (const char *)send_pkg->_data, send_pkg->_write_pos);
//	Printf("[image]write_func DoSend: ret = %d\n", ret);
//        DeleteBuffer(&send_pkg);
//        
//	flag++;
//       my_upload.image_tick = sys_now();
//    }

    if(flag == 0)
    {
        sys_msleep(200);
    }
    
    return ret;
}
int client_process_func(void* arg)
{
    int sockfd = *(int*)arg;
    fd_set readset;
    fd_set writeset;
    int i, maxfdp1;
	
    for (;;)
    {
        maxfdp1 = sockfd+1;
	
        /* Determine what sockets need to be in readset */
        FD_ZERO(&readset);
        FD_ZERO(&writeset);
        FD_SET(sockfd, &readset);
        FD_SET(sockfd, &writeset);
        i = select(maxfdp1, &readset, &writeset, 0, 0);
        
        if (i == 0)
            continue;
				OSTimeDly(1);
			//	Printf("receive data From OneNet\r\n");
        if (FD_ISSET(sockfd, &readset))
        {
            /* This socket is ready for reading*/
            if (recv_func(sockfd) < 0)
                break;
        }
        /* This socket is ready for writing*/
        if (FD_ISSET(sockfd, &writeset))
        {
					if (write_func(sockfd) < 0)
							break;
        }
		
    }

    return -1;
}

void edp_demo(void * arg)
{
    int sockfd, ret,i;
	
    EdpPacket* send_pkg;

  //  arg = arg;

    while(1)
    {
	    /* create a socket and connect to server */
        sockfd = Open((const char *)SERVER_ADDR, SERVER_PORT);
        if (sockfd < 0)
        {
            Printf("server open error\n");
						OSTimeDlyHMSM(0, 0, 2, 0);
            continue;
        }
        /* connect to server */
        send_pkg = PacketConnect1(DEV_ID1,API_KEY);
        Printf("send connect to server, bytes: %d\n", send_pkg->_write_pos);
        ret=DoSend(sockfd, (const char *)send_pkg->_data, send_pkg->_write_pos);
				DeleteBuffer(&send_pkg);
				
        client_process_func((void*)&sockfd);
				/*recv error happen, just close socket*/
        close(sockfd);
        Printf("socket error, close socket and try again\n");

	/*
        c = getchar();
        if (c == '0')
        {
            send_pkg = PacketPing(); 
            Printf("send ping to server, bytes: %d\n", send_pkg->_write_pos);
            DoSend(sockfd, send_pkg->_data, send_pkg->_write_pos);
            DeleteBuffer(&send_pkg);
        }
        else if (c == '1')
        {
#ifdef _DEV1
            send_pkg = PacketPushdata("45523", push_data, sizeof(push_data)); 
#else
            send_pkg = PacketPushdata("25267", push_data, sizeof(push_data)); 
#endif
            Printf("send pushdata to server, bytes: %d\n", send_pkg->_write_pos);
            DoSend(sockfd, send_pkg->_data, send_pkg->_write_pos);
            DeleteBuffer(&send_pkg);
        }
        else if (c == '2')
        {
            save_json=cJSON_Parse(text1);
#ifdef _DEV1
            send_pkg = PacketSavedataJson("45523", save_json); 
#else
            send_pkg = PacketSavedataJson("25267", save_json); 
#endif
            cJSON_Delete(save_json);
            Printf("send savedata json to server, bytes: %d\n", send_pkg->_write_pos);
            DoSend(sockfd, send_pkg->_data, send_pkg->_write_pos);
            DeleteBuffer(&send_pkg);
        }
        else if (c == '3')
        {
            desc_json=cJSON_Parse(text2);
#ifdef _DEV1
            send_pkg = PacketSavedataBin("45523", desc_json, save_bin, sizeof(save_bin)); 
#else
            send_pkg = PacketSavedataBin("25267", desc_json, save_bin, sizeof(save_bin)); 
#endif
            cJSON_Delete(desc_json);
            Printf("send savedata bin to server, bytes: %d\n", send_pkg->_write_pos);
            DoSend(sockfd, send_pkg->_data, send_pkg->_write_pos);
            DeleteBuffer(&send_pkg);
        }

        */
    }
    
    //return 0;
}
void onenet_task_int(void)
{
	 sys_thread_new("edp_demo", edp_demo, 0, 1024, TCPIP_THREAD_PRIO + 1);   
}